package com.knoya.chejian.pda.module.zupan

import android.app.Activity
import android.app.ActivityManager
import android.app.AlertDialog
import android.content.*
import android.text.Editable
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import com.knoya.chejian.pda.R
import com.knoya.chejian.pda.activity.BaseActivity
import com.knoya.chejian.pda.minterface.OnUserDataInterface
import com.knoya.chejian.pda.module.zupan.pan.PanActivity
import com.knoya.chejian.pda.module.zupan.pan.YiPanActivity
import com.knoya.chejian.pda.module.zupanchaxun.ZupanChakanM
import com.knoya.chejian.pda.myadapter.ArrayAdapter
import com.knoya.chejian.pda.myadapter.ZupanAdapter
import com.knoya.chejian.pda.myadapter.ZupanChaxunAdapter
import com.knoya.chejian.pda.util.FileUtils
import com.knoya.chejian.pda.util.JsonUtil
import com.knoya.chejian.pda.util.Myutil
import kotlinx.android.synthetic.main.activity_zupan.*
import kotlinx.android.synthetic.main.header_knoya.*
import org.json.JSONException
import org.json.JSONObject
import java.util.regex.Pattern

class ZupanActivity : BaseActivity(), View.OnClickListener {

    val chaxunfangshi = ArrayList<String>()
    lateinit var pcodes : ArrayList<ZupanBean>
    lateinit var M : ZupanM
    lateinit var dialog: AlertDialog
    lateinit var zupanadapter : ZupanAdapter
    lateinit var zupcodes : ArrayList<ZupanBean>
    lateinit var yuanpcodes : ArrayList<ZupanBean>
    var weisao = 0
    var yisao = 0
    var issao = false
    var issaoyunxu = true
    var no_mark = ArrayList<String>()
//    val gaodus = ArrayList<String>()
    lateinit var lisguolvweizhi : ArrayList<String>
    override fun getLayoutId(): Int {
        when(jiemian){
            1 -> return R.layout.activity_zupan
            2 -> return R.layout.activity_zupan_2
        }
        return R.layout.activity_zupan

    }

    override fun initCreate() {
        no_mark.add("Q")
        no_mark.add("A")
        no_mark.add("PC")
        no_mark.add("T")
        no_mark.add("UB")
        no_mark.add("UH")
        no_mark.add("QR")
        no_mark.add("QS")
        no_mark.add("GD")

        iv_header_left.visibility = View.VISIBLE
        tv_header_title.text = "组盘"
        iv_header_left.setOnClickListener(this)
        Bt_YiPan.setOnClickListener(this)
        M = ZupanM()
        chaxunfangshi.add("按订单")
        chaxunfangshi.add("按柜号")
        chaxunfangshi.add("按包号")
        when(jiemian){
            1 -> {
                val adapter = ArrayAdapter(this, R.layout.lv_sp_tvitem, chaxunfangshi)
                Sp_zupan_Chaxun.adapter = adapter
            }
            2 ->{
                val adapter = ArrayAdapter(this, R.layout.lv_sp_tvitem_2, chaxunfangshi)
                Sp_zupan_Chaxun.adapter = adapter
            }
        }

        pcodes = ArrayList()
        zupcodes = ArrayList()
        yuanpcodes = ArrayList()
        zupanadapter = ZupanAdapter(pcodes,this)
        Lv_Zupan.adapter = zupanadapter

//        tv_header_title.isFocusable = true
//        tv_header_title.isFocusableInTouchMode = true
//        tv_header_title.requestFocus()
//        tv_header_title.requestFocusFromTouch()

        Bt_Zupan_Ok.setOnClickListener(this)
        Bt_Kaishi_Zupan.setOnClickListener(this)
        Bt_Xiazai.setOnClickListener(this)
//        Tv_Pallet_num.setOnClickListener(this)
        /**
         * 广播接受着，用于在退出时关闭activity
         */
        mBoradcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                if(!isAPPBroughtToBackground()){
                    return
                }
                if(!issaoyunxu){
                    return
                }
                if (intent.action == "nlscan.action.SCANNER_RESULT" && intent.hasExtra("SCAN_BARCODE1")) {
                    val scanResult_1 = intent.getStringExtra("SCAN_BARCODE1").trim()
                    samiaoOk(scanResult_1)
                }
                if(intent.action == "android.intent.ACTION_DECODE_DATA" && intent.hasExtra("barcode_string")){
                    val scanResult = intent.getStringExtra("barcode_string").trim()
                    samiaoOk(scanResult)
                }
            }
        }
        var wei = sp.getString("weizhiguolv","")
        var weis = wei.split("&&")
        lisguolvweizhi = ArrayList()
        for (s in weis){
            lisguolvweizhi.add(s)
        }
        Et_Pcode.setOnEditorActionListener { _, actionId, _ ->
            var isOK = true
            isOK
        }
//        gaodus.add("800mm")
//        gaodus.add("600mm")
//        val adapter = ArrayAdapter(this, R.layout.lv_sp_tvitem, gaodus)
//        Sp_Gaodu.adapter = adapter
    }


    //扫描获取到数据后处理
    fun samiaoOk(data : String){
        if(data.length>28){
            Myutil.tishidialog(this@ZupanActivity,"条码扫描错误，请重新扫描")
            Myutil.zhendong(this)
            FileUtils.playSound(R.raw.baojing);
        }
        var pattern = Pattern.compile("[0-9]*")
        var ishuszi = pattern.matcher(data).matches()
        var str=data.substring(0,2)
        if(str == "TP" || str == "AP"){
            Et_Pallet_num.setText(data)
        }else if(data.length == 6 && ishuszi){
            Et_Weizhi.setText(data)
        }else{
            if(issao) {
                ispcodes(data)
                zupanadapter.notifyDataSetChanged()
            }else{
                Et_Pcode.setText(data)
            }
        }

    }
    override fun onClick(v: View?) {
        when(v){
//            Tv_Pallet_num -> {
//                val intent = Intent(this, PanActivity::class.java)
//                intent.putExtra("gaodu", gaodu)
//                intent.putExtra("weizhi", weizhi)
//                intent.putExtra("pallet_num", pallet_num)
//                startActivityForResult(intent,50)
//            }
            iv_header_right ->{
                val intent = Intent(this, PanActivity::class.java)
                intent.putExtra("pallet_num", Et_Pallet_num.text.toString())
                startActivityForResult(intent,50)
            }
            Bt_Xiazai -> {
                if(Et_Pcode.text.toString().trim() == ""){
                    Myutil.tishidialog(this,"需要扫描或者输入条码后才能下载")
                    return
                }
                dialog = Myutil.showupdatedialog(this@ZupanActivity, "正在获取数据", false)
                M.getdata(this,Sp_zupan_Chaxun.selectedItem.toString(),Et_Pcode.text.toString(),object : OnUserDataInterface{
                    override fun onUserData(data: String?) {
                        Log.d("TAAG",data)
                        if(data == null){
                            return
                        }
                        jsondata(data)
                        Bt_Kaishi_Zupan.text = "开始组盘"
                        issao = false
                        zupcodes.clear()
                    }

                    override fun onNot(throwable: String?) {
                        dialog.dismiss()
                    }
                })
            }
            Bt_Zupan_Ok -> {
//                if(Sp_Gaodu.selectedItem.toString() == "800mm"){
//                    gaodu = "800";
//                }else if(Sp_Gaodu.selectedItem.toString() == "600mm"){
//                    gaodu = "600";
//                }else{
//                    gaodu = "0";
//                }
                gaodu = "800";
                weizhi = Et_Weizhi.text.toString()
                pallet_num = Et_Pallet_num.text.toString()
                if(pallet_num == ""){
                    Myutil.tishidialog(this,"需要扫描托盘后才能更新组盘")
                    return
                }
                if(!issao){
                    Myutil.tishidialog(this,"需要开始扫描后才能更新组盘")
                    return
                }
                if(zupcodes.size == 0){
                    Myutil.tishidialog(this,"需要扫描包之后才能更新组盘")
                    return
                }
                if(weizhi == ""){
                    Myutil.tishidialog(this,"需要输入位置后才能更新组盘")
                    return
                }
                dialog = Myutil.showupdatedialog(this@ZupanActivity, "正在上传数据", false)
                M.postzupan(this,gaodu,weizhi,pallet_num,zupcodes,object :OnUserDataInterface{
                    override fun onUserData(data: String?) {
                        Log.d("TAAG",data)
                        var status = ""
                        var msg = ""
                        try {
                            var jo = JSONObject(data)
                            status = JsonUtil.getvolue(jo,"status")
                            msg = JsonUtil.getvolue(jo ,"msg")
                        }catch (e : JSONException){
                            e.printStackTrace()
                        }
                        if(msg != ""){
                            Myutil.tishidialog(this@ZupanActivity,msg)
                        }
                        dialog.dismiss()
                        if(status != "success"){
                            return
                        }
                        yuanpcodes.clear()
                        pcodes.clear()
                        zupcodes.clear()
                        Tv_Tishi.text = ""
                        zupanadapter.notifyDataSetChanged()
                        Bt_Kaishi_Zupan.text = "开始组盘"
                        issao = false

                    }

                    override fun onNot(throwable: String?) {
                        dialog.dismiss()
                    }

                })
            }
            Bt_Kaishi_Zupan -> {
                if(issao){
                    Bt_Kaishi_Zupan.text = "开始组盘"
                    issao = false
                    zupcodes.clear()
                    pcodes.clear()
                    for (bean in yuanpcodes){
                        pcodes.add(bean)
                    }
                    zongbaoshu()
                    Tv_Tishi.text = "总包数： "+zongbaoshu+" 未组盘:"+weizu+" 已组盘："+yizu
                }else{
                    issao = true
                    Bt_Kaishi_Zupan.text = "停止组盘"
                    saoshu()
                }
            }
            iv_header_left -> {
                finish()
            }
            Bt_YiPan -> {
                if(Et_Pallet_num.text.toString().trim() == ""){
                    Myutil.tishidialog(this@ZupanActivity,"输入托盘后才能移盘")
                    return
                }
                val intent = Intent(this, YiPanActivity::class.java)
                intent.putExtra("pallet_num", Et_Pallet_num.text.toString().trim())
                startActivityForResult(intent,50)
            }
        }
    }


    private fun saoshu(){
        weisao = 0
        yisao = zupcodes.size
//        for (bean in zupcodes){
//            if(no_mark.contains(bean.mc_p_mark)){
//                yisao--
//            }
//        }
        for (bean in pcodes){
            if(no_mark.contains(bean.mc_p_mark)){
                continue
            }
            if("初始" == bean.status_name){
                weisao++
            }
            if(bean.pallet_num != ""){
                if(bean.pallet_num.substring(0,2) ==  "AP"){
                    weisao++
                }
            }
            if(bean.wp_warehouse == "10"){
                weisao++
            }
        }
        Tv_Tishi.text = "未扫描："+weisao+" 已扫描:"+yisao
    }

//    //不在二楼组盘的类别
//    var no_mc_p_marks = arrayOf("Q","A","PC","T","UF","UB","UH","QR","QS","GD")
//    //判断这个类别是否在二楼组盘
//    fun isno_mc_p_mark(mark : String):Boolean{
//        return no_mc_p_marks.contains(mark)
//    }

    fun jsondata(data : String){
        var panbean = ZupanBean()
        panbean.zp_ctime = "0"
        yuanpcodes.clear()
        var status = ""
        var msg = ""
        try {
            var jo = JSONObject(data)
            status = JsonUtil.getvolue(jo,"status")
            var js = JsonUtil.getjsvolue(jo,"data")
            msg = JsonUtil.getvolue(jo ,"msg")
            for(i in 0 until js.length()){
                var pcodejo = js[i] as JSONObject
                //如果这包货不在二楼组盘则跳过
                var bean = ZupanBean()
                bean.onum = JsonUtil.getvolue(pcodejo,"onum")
                bean.status_name = JsonUtil.getvolue(pcodejo,"status_name")
                bean.pallet_num = JsonUtil.getvolue(pcodejo,"pallet_num")
                bean.zp_ctime = JsonUtil.getvolue(pcodejo,"zp_ctime")
                bean.intime = JsonUtil.getvolue(pcodejo,"intime")
                bean.pcode = JsonUtil.getvolue(pcodejo,"pcode")
                bean.pallet_height = JsonUtil.getvolue(pcodejo,"pallet_height")
                bean.pallet_position_buffer = JsonUtil.getvolue(pcodejo,"pallet_position_buffer")
                bean.position = JsonUtil.getvolue(pcodejo,"position")
                bean.wp_warehouse = JsonUtil.getvolue(pcodejo,"warehouse")
                bean.mc_p_mark = JsonUtil.getvolue(pcodejo,"mc_p_mark")
                yuanpcodes.add(bean)
                if(bean.pallet_num == ""){
                    continue
                }
                var isguolu = false

                    for (gl in lisguolvweizhi){

                        if(gl == ""){
                            continue
                        }
                        var str ="";
                        if(bean.pallet_position_buffer.length >= gl.length){
                            str = bean.pallet_position_buffer.substring(0,gl.length)
                            if(str == gl){
                                Log.d("TAAAG",bean.pallet_position_buffer)
                                isguolu = true
                                continue
                            }
                        }
                    }
                if(isguolu){
                    continue
                }
                if(bean.zp_ctime != ""){
                    if(bean.zp_ctime.toInt() > panbean.zp_ctime.toInt() && bean.intime == ""){
                        panbean = bean
                    }
                }
            }
        }catch (e : JSONException){
            e.printStackTrace()
            Log.d("TAAG",e.toString())
        }

        if(status == "success"){
            var pan = ""
            if(panbean.pallet_num != ""){
                pan += panbean.pallet_num
                if(panbean.pallet_height != ""){
                    pan += panbean.pallet_height
                }

//                pallet_num = panbean.pallet_num
            }
            if(panbean.pallet_height == "800mm"){
                gaodu = "800"
            }else if(panbean.pallet_height == "600mm"){
                gaodu = "600"

            }
            weizhi = panbean.pallet_position_buffer

//            Tv_Pallet_num.text = panbean.pallet_num+" 位置:"+weizhi+" 高度:"+gaodu
            pcodes.clear()
            for (bean in yuanpcodes){
                pcodes.add(bean)
            }
            zupanadapter.notifyDataSetChanged()
        }else if(status == "error"){
        }
        zongbaoshu()
        Tv_Tishi.text = "总包数： "+zongbaoshu+" 未组盘:"+weizu+" 已组盘："+yizu
        if(msg != ""){
            Myutil.tishidialog(this,msg)
        }
//        if(gaodu == "800"){
//            Sp_Gaodu.setSelection(0)
//        }else if(gaodu == "600"){
//            Sp_Gaodu.setSelection(1)
//        }
        Et_Pallet_num.setText("")
        Et_Weizhi.setText(weizhi)
        dialog.dismiss()
    }
    var zongbaoshu = 0
    var weizu = 0
    var yizu = 0
    private fun zongbaoshu(){
        zongbaoshu = 0
        weizu = 0
        yizu = 0
        zongbaoshu = 0
        for (bean in yuanpcodes){
            if(bean.zp_ctime != ""){
                yizu++
            }
            if(no_mark.contains(bean.mc_p_mark)){
                continue
            }
            zongbaoshu ++;
            if("初始" == bean.status_name){
                weizu++
            }
            if(bean.pallet_num != ""){
                if(bean.pallet_num.substring(0,2) ==  "AP"){
                    weizu++
                }
            }
            if(bean.wp_warehouse == "10"){
                weizu++
            }

        }
    }

    var gaodu = ""
    var weizhi = ""
    var pallet_num = ""
//    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        if(data==null){
//            return
//        }
//        when (requestCode) {
//            50 -> if (resultCode == Activity.RESULT_OK) {
//                gaodu = data.getStringExtra("gaodu").trim()
//                weizhi = data.getStringExtra("weizhi").trim()
//                pallet_num = data.getStringExtra("pallet_num").trim()
//                Tv_Pallet_num.text = pallet_num+" 位置:"+weizhi+" 高度:"+gaodu
//            }
//        }
//    }

    fun isAPPBroughtToBackground(): Boolean {
        val am = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val tasks = am.getRunningTasks(1)
        if (!tasks.isEmpty()) {
            val topActivity = tasks[0].topActivity
            if (topActivity.className == this.javaClass.name) {

                return true
            }
        }
        return false
    }
    private fun ispcodes(pcode :String) {
        Log.d("TAAG",pcode)
        for (bean in zupcodes){
            if(pcode == bean.pcode){
                Myutil.MyTost("这包货已经扫描过")
                Myutil.zhendong(this)
                FileUtils.playSound(R.raw.baojing);
                return
            }
        }
        for (bean  in pcodes){
            if(pcode == bean.pcode){
                zupcodes.add(bean)
                pcodes.remove(bean)
                saoshu()
                return
            }
        }
        issaoyunxu = false
        Myutil.tishidismissdialog(this, "没找到条码$pcode",object : DialogInterface.OnDismissListener{
            override fun onDismiss(dialog: DialogInterface?) {
                issaoyunxu = true
            }
        })
    }


}
